/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mask;

import java.awt.image.BufferedImage;
import java.awt.image.Raster;

/**
 *
 * @author tommy
 */
public class ImageMask {
	private double[][] mask; // mask values
	private int n; // mask dimension
	
	public ImageMask(double[][] mask, int n) throws IllegalArgumentException {
		if (n % 2 == 0) {
			throw new IllegalArgumentException("Mask dimensions must be odd");
		}
		
		this.n = n;
		this.mask = mask;
	}
	
	// Applies nxn mask in the sorroundings of pixel (x,y)
	public Double[] applyMask(BufferedImage src) throws IndexOutOfBoundsException {
		// n/2 * 2 != n because integer round is performed in n/2
		Double[] maskRet = new Double[(src.getHeight() - n/2 * 2)*(src.getWidth()-n/2 * 2)];
		double maskVal = 0;
		Raster srcRaster = src.getData();
		int k = 0;
		
		if (src.getType() != BufferedImage.TYPE_BYTE_GRAY) {
			return null;
		}
	
		// for each pixel in image, apply mask using nxn kernel.
		// (padded borders excluded)
		
		for (int y = n/2 ; y < src.getHeight() - n/2; y++) {
			for (int x = n/2 ; x < src.getWidth() - n/2; x++, maskVal = 0) {
				for (int i = 0 ; i < n ; i++) {
					for (int j = 0 ; j < n ; j++) {
						maskVal += mask[i][j] * srcRaster.getSample(x + j-n/2, y + i - n/2, 0);
					}
				}
				// mask applied, store resultant value
				maskRet[k++] = maskVal;
			}
		}
		return maskRet; // returns masked value for each pixel
	}
}
